<template>
  <div class="problem-detail">
    <el-row :gutter="20" class="full-height">
      <!-- 左侧题目描述 -->
      <el-col :span="12" class="description-panel">
        <el-card class="full-height">
          <template #header>
            <div class="problem-header">
              <div class="title-section">
                <h2>{{ problem.title }}</h2>
                <el-tag :type="getDifficultyType(problem.hardLevel)">
                  {{ problem.hardLevel }}
                </el-tag>
              </div>
              <div class="action-buttons">
                <div class="button-group">
                  <!-- 添加编辑按钮 -->
                  <el-button type="primary" @click="handleEdit" v-if="isAdmin">
                    <el-icon><Edit /></el-icon>
                    编辑题目
                  </el-button>
                  <el-button type="primary" @click="showDiscussions = true">
                    <el-icon><ChatLineRound /></el-icon>
                    讨论区
                  </el-button>
                  <el-button type="success" @click="showAddDiscussion = true">
                    <el-icon><Plus /></el-icon>
                    发布讨论
                  </el-button>
                </div>
              </div>
            </div>
          </template>
          <div class="markdown-body">
            <MdPreview :modelValue="problem.problemDescription" />
          </div>
        </el-card>
      </el-col>

      <!-- 右侧代码编辑器 -->
      <el-col :span="12" class="code-panel">
        <el-card class="full-height">
          <template #header>
            <div class="code-header">
              <el-select v-model="language" placeholder="选择编程语言" style="width: 120px">
                <el-option label="C" value="cpp" />
                <el-option label="C++" value="cpp" />
                <el-option label="Python" value="python" />
                <el-option label="Java" value="java" />
                <el-option label="JavaScript" value="javascript" />
                <el-option label="Rust" value="rust" />
                <el-option label="PHP" value="php" />
                <el-option label="C#" value="csharp" />
                <el-option label="Go" value="go" />
              </el-select>
              <el-button 
                type="primary" 
                @click="handleSubmit"
                :loading="submitting"
              >
                提交代码
              </el-button>
            </div>
          </template>
          
          <div class="editor-container">
            <Codemirror
              v-model="code"
              :style="{ height: '100%' }"
              :autofocus="true"
              :indent-with-tab="true"
              :tab-size="2"
              :extensions="extensions"
            />
          </div>

          <!-- 提交结果弹窗 -->
          <el-dialog
            v-model="showResult"
            title="提交结果"
            width="30%"
            :close-on-click-modal="false"
          >
            <div class="result-content">
              <el-result
                :icon="resultIcon"
                :title="resultTitle"
                :sub-title="submitResult.evaluate"
              >
                <template #extra>
                  <div class="score-info">
                    得分：{{ submitResult.score }}
                  </div>
                  <div class="similarity-info">
                    查重率：{{ submitResult.codeSimilarity || 0 }}%
                  </div>
                </template>
              </el-result>
            </div>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="showResult = false">关闭</el-button>
              </span>
            </template>
          </el-dialog>
        </el-card>
      </el-col>

      <!-- 讨论区弹窗 -->
      <el-dialog
        v-model="showDiscussions"
        title="讨论区"
        width="60%"
        :destroy-on-close="true"
      >
        <div class="discussions-container">
          <el-scrollbar height="500px">
            <div v-if="discussionList.length > 0">
              <el-card v-for="item in discussionList" :key="item.id" class="discussion-item">
                <template #header>
                  <div class="discussion-header">
                    <div class="user-info">
                      <el-avatar :size="32" :src="item.avatarUrl" />
                      <span class="username">{{ item.userAccount }}</span>
                    </div>
                    <div class="discussion-stats">
                      <span class="time">{{ formatDateTime(item.createTime) }}</span>
                      <el-button 
                        :type="item.isLiked ? 'primary' : 'default'"
                        size="small"
                        text
                        @click="handleLike(item)"
                      >
                        <el-icon>
                          <component :is="item.isLiked ? StarFilled : Star" />
                        </el-icon>
                        {{ item.likesCount }}
                      </el-button>
                      <el-button 
                        type="primary" 
                        size="small" 
                        text
                        @click="handleShowReply(item)"
                      >
                        <el-icon><ChatDotRound /></el-icon>
                        {{ item.replyCount }}
                      </el-button>
                    </div>
                  </div>
                </template>
                <h4>{{ item.title }}</h4>
                <p>{{ item.content }}</p>
                
                <!-- 添加回复列表 -->
                <div class="replies-section">
                  <el-collapse>
                    <el-collapse-item>
                      <template #title>
                        <span class="replies-count">{{ item.replyCount }} 条回复</span>
                      </template>
                      <div class="replies-list">
                        <div v-if="item.replies && item.replies.length > 0">
                          <div v-for="reply in item.replies" :key="reply.id" class="reply-item">
                            <div class="reply-header">
                              <div class="user-info">
                                <el-avatar :size="24" :src="reply.avatarUrl" />
                                <span class="username">{{ reply.userAccount }}</span>
                                <span class="time">{{ formatDateTime(reply.createTime) }}</span>
                              </div>
                              <div class="reply-actions">
                                <el-button 
                                  :type="reply.isLiked ? 'primary' : 'default'"
                                  size="small"
                                  text
                                  @click="handleReplyLike(reply)"
                                >
                                  <el-icon>
                                    <component :is="reply.isLiked ? StarFilled : Star" />
                                  </el-icon>
                                  {{ reply.likesCount }}
                                </el-button>
                              </div>
                            </div>
                            <p class="reply-content">{{ reply.content }}</p>
                          </div>
                        </div>
                        <el-empty v-else description="暂无回复" />
                      </div>
                    </el-collapse-item>
                  </el-collapse>
                </div>
              </el-card>
            </div>
            <el-empty v-else description="暂无讨论" />
          </el-scrollbar>
        </div>
        <div class="discussions-pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-dialog>
    </el-row>
    <!-- 添加发布讨论的对话框 -->
    <el-dialog
      v-model="showAddDiscussion"
      title="发布讨论"
      width="50%"
    >
      <el-form :model="discussionForm" :rules="discussionRules" ref="discussionFormRef">
        <el-form-item label="标题" prop="title">
          <el-input v-model="discussionForm.title" placeholder="请输入讨论标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="discussionForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入讨论内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDiscussion = false">取消</el-button>
          <el-button type="primary" @click="handleAddDiscussion" :loading="submittingDiscussion">
            发布
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 添加回复对话框 -->
    <el-dialog
      v-model="showReplyDialog"
      title="发布回复"
      width="40%"
    >
      <el-form :model="replyForm" :rules="replyRules" ref="replyFormRef">
        <el-form-item label="回复内容" prop="content">
          <el-input
            v-model="replyForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showReplyDialog = false">取消</el-button>
          <el-button type="primary" @click="handleAddReply" :loading="submittingReply">
            发布
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, reactive } from 'vue'
import { Codemirror } from 'vue-codemirror'
import { python } from '@codemirror/lang-python'
import { cpp } from '@codemirror/lang-cpp'
import { javascript } from '@codemirror/lang-javascript'
import { oneDark } from '@codemirror/theme-one-dark'
import { useRoute, useRouter } from 'vue-router'
import { MdPreview } from 'md-editor-v3'
import 'md-editor-v3/lib/preview.css'
import { submitCode } from '../../api/submission'
import { ElMessage } from 'element-plus'
import { getProblemDetail } from '../../api/problem'
import { ChatLineRound, ChatDotRound, Star, StarFilled, Plus, Edit } from '@element-plus/icons-vue'
import { getDiscussionList, addDiscussion, addReply } from '../../api/discussion'
import { getDiscussionReplies } from '../../api/discussion'
import { toggleLike } from '../../api/like'  // 添加这行

const route = useRoute()
const router = useRouter()
const language = ref('python')
const code = ref('')
const submitting = ref(false)
const showResult = ref(false)
const problem = ref({})
const submitResult = ref({})

// 获取题目信息
const fetchProblemDetail = async () => {
  try {
    const res = await getProblemDetail(route.params.id)
    if (res.code === 200) {
      problem.value = res.data
    } else {
      ElMessage.error('获取题目详情失败')
    }
  } catch (error) {
    console.error('获取题目详情失败:', error)
    ElMessage.error('获取题目详情失败')
  }
}

const handleSubmit = async () => {
  if (!code.value.trim()) {
    ElMessage.warning('请输入代码')
    return
  }

  submitting.value = true
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    const res = await submitCode({
      code: code.value,
      problemId: Number(route.params.id),
      type: language.value,
      userId: userInfo.id
    })
    
    if (res.code === 200) {
      // 更新提交结果
      submitResult.value = {
        score: res.data.score,
        evaluate: res.data.evaluate,
        codeSimilarity: res.data.codeSimilarity
      }
      // 显示结果弹窗
      showResult.value = true
    } else {
      ElMessage.error(res.message || '提交失败')
    }
  } catch (error) {
    console.error('提交代码失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitting.value = false
  }
}

const resultIcon = computed(() => {
  return submitResult.value.score === 100 ? 'success' : 'warning'
})

const resultTitle = computed(() => {
  return submitResult.value.score === 100 ? '通过' : '未通过'
})

const getDifficultyType = (difficulty) => {
  const types = {
    '简单': 'success',
    '中等': 'warning',
    '困难': 'danger'
  }
  return types[difficulty] || 'info'
}

onMounted(() => {
  fetchProblemDetail()
})

const extensions = computed(() => {
  const langExtension = {
    'python': python(),
    'cpp': cpp(),
    'java': javascript()
  }[language.value] || python()
  
  return [
    langExtension,
    oneDark
  ]
})

// 添加新的响应式变量
const showDiscussions = ref(false)
const discussionList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString()
}

// 获取讨论列表
const fetchDiscussions = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    const res = await getDiscussionList({
      problemId: route.params.id,
      current: currentPage.value,
      pageSize: pageSize.value,
      userId: userInfo?.id
    })
    
    if (res.code === 200) {
      discussionList.value = res.data.records
      total.value = res.data.total
      
      // 获取每个讨论的回复
      for (const discussion of discussionList.value) {
        const repliesRes = await getDiscussionReplies(discussion.id, userInfo?.id)
        if (repliesRes.code === 200) {
          discussion.replies = repliesRes.data
        }
      }
    }
  } catch (error) {
    console.error('获取讨论列表失败:', error)
    ElMessage.error('获取讨论列表失败')
  }
}

// 监听弹窗显示状态
watch(showDiscussions, (newVal) => {
  if (newVal) {
    fetchDiscussions()
  }
})

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchDiscussions()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchDiscussions()
}

// 修改讨论点赞处理函数
const handleLike = async (item) => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    const res = await toggleLike({
      targetId: item.id,
      type: 0,  // 0 表示讨论点赞
      userId: userInfo.id
    })
    
    if (res.code === 200) {
      if (item.isLiked) {
        item.likesCount--
      } else {
        item.likesCount++
      }
      item.isLiked = !item.isLiked
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 添加回复点赞处理函数
const handleReplyLike = async (reply) => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    const res = await toggleLike({
      targetId: reply.id,
      type: 1,  // 1 表示回复点赞
      userId: userInfo.id
    })
    
    if (res.code === 200) {
      if (reply.isLiked) {
        reply.likesCount--
      } else {
        reply.likesCount++
      }
      reply.isLiked = !reply.isLiked
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// Add these new properties
const isAdmin = computed(() => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    return userInfo.role === 'admin'  // 修改这里，使用 role 而不是 userRole
  } catch {
    return false
  }
})

const handleEdit = () => {
  router.push(`/problem/edit/${route.params.id}`)
}

// 添加新的响应式变量部分添加
const showAddDiscussion = ref(false)
const submittingDiscussion = ref(false)
const discussionFormRef = ref(null)

const discussionForm = reactive({
  title: '',
  content: ''
})

const discussionRules = {
  title: [
    { required: true, message: '请输入讨论标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在 2 到 50 个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入讨论内容', trigger: 'blur' },
    { min: 10, max: 500, message: '内容长度在 10 到 500 个字符之间', trigger: 'blur' }
  ]
}

// 添加发布讨论的方法
const handleAddDiscussion = async () => {
  if (!discussionFormRef.value) return
  
  await discussionFormRef.value.validate(async (valid) => {
    if (valid) {
      submittingDiscussion.value = true
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'))
        const res = await addDiscussion({
          title: discussionForm.title,
          content: discussionForm.content,
          problemId: Number(route.params.id),
          userId: userInfo.id
        })
        
        if (res.code === 200) {
          ElMessage.success('发布成功')
          showAddDiscussion.value = false
          // 重新获取讨论列表
          fetchDiscussions()
          // 重置表单
          discussionForm.title = ''
          discussionForm.content = ''
        } else {
          ElMessage.error(res.message || '发布失败')
        }
      } catch (error) {
        console.error('发布讨论失败:', error)
        ElMessage.error('发布失败')
      } finally {
        submittingDiscussion.value = false
      }
    }
  })
}

// 添加回复相关的响应式变量
const showReplyDialog = ref(false)
const submittingReply = ref(false)
const replyFormRef = ref(null)
const currentDiscussion = ref(null)

const replyForm = reactive({
  content: ''
})

const replyRules = {
  content: [
    { required: true, message: '请输入回复内容', trigger: 'blur' },
    { min: 2, max: 500, message: '内容长度在 2 到 500 个字符之间', trigger: 'blur' }
  ]
}

// 显示回复对话框
const handleShowReply = (discussion) => {
  currentDiscussion.value = discussion
  showReplyDialog.value = true
}

// 添加回复的方法
const handleAddReply = async () => {
  if (!replyFormRef.value) return
  
  await replyFormRef.value.validate(async (valid) => {
    if (valid) {
      submittingReply.value = true
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'))
        const res = await addReply({
          content: replyForm.content,
          discussionId: currentDiscussion.value.id,
          userId: userInfo.id
        })
        
        if (res.code === 200) {
          ElMessage.success('回复成功')
          showReplyDialog.value = false
          // 重新获取讨论列表
          fetchDiscussions()
          // 重置表单
          replyForm.content = ''
          currentDiscussion.value = null
        } else {
          ElMessage.error(res.message || '回复失败')
        }
      } catch (error) {
        console.error('发布回复失败:', error)
        ElMessage.error('回复失败')
      } finally {
        submittingReply.value = false
      }
    }
  })
}
</script>

<style scoped>
.problem-detail {
  height: calc(100vh - 60px);
  padding: 20px;
}

.full-height {
  height: 100%;
}

.description-panel, .code-panel {
  height: 100%;
}

.problem-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.editor-container {
  height: calc(100% - 20px);
}

.markdown-body {
  padding: 0 10px;
  overflow-y: auto;
  height: calc(100% - 20px);
}

.result-content {
  text-align: center;
}

.score-info {
  font-size: 18px;
  color: #409EFF;
  margin-top: 10px;
}

.similarity-info {
  font-size: 18px;
  color: #E6A23C;
  margin-top: 10px;
}
:deep(.el-card__body) {
  height: calc(100% - 60px);
  padding: 10px;
}

.discussions-container {
  min-height: 500px;
}

.discussion-item {
  margin-bottom: 16px;
}

.discussion-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.username {
  font-weight: bold;
}

.discussion-stats {
  display: flex;
  align-items: center;
  gap: 16px;
}

.time {
  color: #999;
  font-size: 14px;
}

.discussions-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.action-buttons {
  display: flex;
  align-items: center;
}

.button-group {
  display: flex;
  gap: 10px;
}

/* 移除之前的 discussion-buttons 样式 */
</style>